package com.example.gateway.filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * packageName com.example.gateway.filter
 *
 * @author cui haida
 * @version JDK 8
 * 2025/8/5
 */
@Component
public class SmsCaptchaFilter extends AbstractGatewayFilterFactory<SmsCaptchaFilter.Config> {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            if (!request.getPath().value().equals("/auth/login")) {
                return chain.filter(exchange);
            }

            String phone = request.getHeaders().getFirst("X-Phone");
            String smsCode = request.getHeaders().getFirst("X-Sms-Code");

            if (phone == null || smsCode == null) {
                return badRequest(exchange, "Missing SMS code");
            }

            String storedCode = redisTemplate.opsForValue().get("SMS_CODE:" + phone);
            if (storedCode == null || !storedCode.equals(smsCode)) {
                return badRequest(exchange, "Invalid SMS code");
            }

            redisTemplate.delete("SMS_CODE:" + phone);
            return chain.filter(exchange);
        };
    }

    private Mono<Void> badRequest(ServerWebExchange exchange, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.BAD_REQUEST);
        response.getHeaders().add("Content-Type", "text/plain");
        return response.writeWith(Mono.just(response.bufferFactory().wrap(message.getBytes())));
    }

    public static class Config {}
}